/* eslint-disable linebreak-style */
import React, { PureComponent } from 'react';
import { Card, Form, Col, Row, Popconfirm, DatePicker, Input, Select, message, Button } from 'antd';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import FooterToolbar from '@/components/FooterToolbar/index';
import styles from './style.less';
// import { getDicByCodeSort } from '@/utils/common';
import {findDicByCode, getDictOptionsByCode} from '@/support/common';

const { Option } = Select;

const fieldLabels = {
  projectId: '项目',
  vin: 'VIN',
  brandId: '品牌',
  styleId: '车型',
  seriesId: '车系',
  status: '车辆状态',
  licence: '车牌',
  colorId: '颜色',
  doptCode: '发动机号',
  insuranceId: '保险公司',
  dealerId: '经销商',
  assType: 'assType',
  pin: '安全码',
  pinValidDate: '安全码有效时间',
  language: '车机语言',
  enrollStatus: '激活状态',
  produceDate: '生产日期',
  publishDate: '发布日期',
  realVin: '真实VIN',
  vhlType: '车辆类型',
  remarks: '备注',
};


@connect(state => ({
  vehicle: state.vehicle,
  currentUser: state.user.currentUser,
}))
// @Form.create()
export default class VehicleSave extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.any,
  };
  state = {
    seriesOptions: [],
    typeOptions: [],
    colorOptions: [],
    dealerOptions: [],
    buttonLoading: false,
    projectOptions: [],
    brandOptions: [],
  };
  componentWillMount() {
  }
  componentDidMount() {
    this.props.dispatch({
      type: 'basedata/brandFetch',
      callback: (res) => {
        this.setState({ 
           brandOptions: res?.data?.map((item)=>{
            return {
              label: item.brandName,
              value: item.brandCode
            }
          }),
          });
        }
    });
    this.props.dispatch({
      type: 'basedata/colorList',
      callback: (response) => {
        this.setState({
          colorOptions: response.filter(item => item.code !== '').map(d => <Option key={d.code}>{d.name}</Option>),
        });
      },
    });
  }

  onBrandSelect = (value) => {
    this.refs.form.setFieldsValue({ seriesId: '', styleId: '', projectId: '', dealerId: ''});
    if (value) {
      this.props.dispatch({
        type: 'basedata/seriesList',
        payload: { brandId: value },
        callback: (response) => {
          if (response) {
            console.log('this.state.projects', this.state.projects)
            this.setState({
              seriesOptions: response.filter(item => item.code !== '').map(d => <Option key={d.code}>{d.name}</Option>),
            });
          } else {
            this.setState({
              seriesOptions: '',
              typeOptions: '',
            });
          }
        },
      });
      //根据品牌查询项目
      this.props.dispatch({
        type: 'basedata/findProjectIdsByBrandCode',
        payload: { brandCode : value },
        callback: (response) => {
          if (response) {
            this.setState({
              projectOptions: response.data.filter(item => item.brandCode === value).map(d => <Option key={d.projectId}>{d.projectName}</Option>),
            });
          } else {
            this.setState({
              projectOptions: '',
            });
          }
        },
      });
      //根据品牌查询经销商
      this.props.dispatch({
        type: 'basedata/findDealerByBrandCode',
        payload: { brandCode : value },
        callback: (response) => {
          if (response) {
            this.setState({
              dealerOptions: response.data.filter(item => item.brandId === value).map(d => <Option key={d.code}>{d.name}</Option>),
            });
          } else {
            this.setState({
              dealerOptions: '',
            });
          }
        },
      });
    } else {
      this.setState({
        seriesOptions: '',
        typeOptions: '',
        projectOptions: '',
        dealerOptions: ''
      });
    }
  }

  onSerieSelect = (value) => {
    this.refs.form.setFieldsValue({ styleId: '' });
    if (value) {
      this.props.dispatch({
        type: 'basedata/typeList',
        payload: { seriesId: value },
        callback: (response) => {
          if (response) {
            this.setState({
              typeOptions: response.filter(item => item.code !== '').map(d => <Option key={d.code}>{d.name}</Option>),
            });
          } else {
            this.setState({
              typeOptions: '',
            });
          }
        },
      });
    } else {
      this.setState({
        typeOptions: '',
      });
    }
  }

  ok = (values) => {
    this.setState({
      buttonLoading: true,
    });
    const obj = values;
    obj.realNameStatus = "0";
    obj.mnoSyncStatus = "0";
    this.props.dispatch({
      type: 'vehicle/add',
      payload: obj,
      callback: (response) => {
        if (response.code === '200') {
          message.success('操作成功');
          this.refs.form.resetFields();
          // dispatch(routerRedux.push('/deviceManager/vehicle'));
          this.props.history.goBack();
        } else {
          message.error(response.description);
        }
        this.setState({
          buttonLoading: false,
        });
      },
    });
  }

  render() {
    const { seriesOptions,
      typeOptions, colorOptions, dealerOptions,
      projectOptions, buttonLoading, brandOptions } = this.state;
      console.log('projectOptions', projectOptions)
    const { form, dispatch } = this.props;
    const { brandCodes = [] } = this.props.currentUser;
    const statusOptions = getDictOptionsByCode(this.context.dicData, 'vehicleStatus');
    const enrollStatusOptions = getDictOptionsByCode(this.context.dicData, 'vehicleEnrollStatus');
    
    enrollStatusOptions.sort((a, b) => a.value - b.value);
    
    const assTypeOptions = getDictOptionsByCode(this.context.dicData, 'vehicleAssType');
    return (
      <PageHeaderLayout
        title=""
        wrapperClassName={styles.advancedForm}
      >
        <Card title="" className={styles.card} bordered={false}>
          <Form ref="form" layout="vertical" onFinish={this.ok} >
            <Row gutter={24}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.brandId} rules={[{ required: true, message: '请选择品牌' }]} name="brandId" >
                  <Select allowClear placeholder="请选择" onChange={this.onBrandSelect} getPopupContainer={triggerNode => triggerNode.parentNode} options={brandOptions} />
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.seriesId} rules={[{ required: false, message: '请输入车系' }]} name="seriesId" >
                  <Select allowClear placeholder="请选择" onChange={this.onSerieSelect} getPopupContainer={triggerNode => triggerNode.parentNode}>
                    {seriesOptions}
                  </Select>
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.styleId} rules={[{ required: false, message: '请选择车型' }]} name="styleId">
                  <Select allowClear placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode}>
                    {typeOptions}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.projectId} rules={[{ required: true, message: '请选择项目' }]} name="projectId">
                  <Select placeholder="请选择项目" getPopupContainer={triggerNode => triggerNode.parentNode}>
                    {projectOptions}
                  </Select>
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.vin} rules={[{ required: true, message: '请输入VIN' }]} name="vin">
                  <Input maxLength="20" placeholder="请输入VIN" />
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.enrollStatus} rules={[{ required: true, message: '请选择激活状态' }]} name="enrollStatus">
                  <Select allowClear placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode} options={enrollStatusOptions} />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.status} rules={[{ required: true, message: '请选择车辆状态' }]} name="status">
                  <Select allowClear placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode} options={statusOptions} />
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.colorId} rules={[{ required: false, message: '请选择颜色' }]} name="colorId" >
                  <Select allowClear placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode}>
                    {colorOptions}
                  </Select>
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.doptCode} rules={[{ required: false, message: '请输入发动机号' }]} name="doptCode">
                  <Input maxLength="17" placeholder="请输入发动机号" />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.licence} rules={[{ required: false, message: '请输入车牌' }]} name="licence">
                  <Input maxLength="10" placeholder="请输入车牌" />
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.assType} rules={[{ required: false, message: '请选择' }]} name="assType">
                  <Select allowClear placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode} options={assTypeOptions} />
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.dealerId} rules={[{ required: false, message: '请选择经销商' }]} name="dealerId">
                  <Select
                    allowClear
                    placeholder="请选择"
                    showSearch
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                    filterOption={(input, option) => option.props.title?.toLowerCase()?.indexOf(input?.toLowerCase()) >= 0}
                  >
                    {dealerOptions}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.realVin} rules={[{ required: false, message: '请输入真实VIN' }]} name="realVin">
                  <Input maxLength="20" placeholder="请输入真实VIN" />
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.pin} rules={[{ required: false, message: '请输入安全码' }]} name="pin">
                  <Input maxLength="32" placeholder="请输入安全码" />
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.pinValidDate} rules={[{ required: false, message: '请输入安全码有效时间' }]} name="pinValidDate">
                  <DatePicker
                    style={{ width: '100%' }}
                    placeholder="请输入安全码有效时间"
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.language} rules={[{ required: false, message: '请输入车机语言' }]} name="language">
                  <Input maxLength="5" placeholder="请输入车机语言" />
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.produceDate} rules={[{ required: false, message: '请输入生产日期' }]} name="produceDate">
                  <DatePicker
                    style={{ width: '100%' }}
                    placeholder="请输入生产日期"
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.publishDate} rules={[{ required: false, message: '请输入发布日期' }]} name="publishDate">
                  <DatePicker
                    style={{ width: '100%' }}
                    placeholder="请输入发布日期"
                    format="YYYY-MM-DD"
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.remarks} rules={[{ required: false, message: '请输入备注' }]} name="remarks">
                  <Input placeholder="请输入备注" />
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <Form layout="vertical" hideRequiredMark>
            <Row gutter={16}>
              <Col xl={{ span: 5, offset: 9 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                <div >
                  <Button loading={buttonLoading} key="submit" type="primary" size="default" onClick={() => this.refs.form.submit()}>
                    提交
                  </Button>
                  &nbsp;&nbsp;
                  <Popconfirm title="确定放弃添加吗?" onConfirm={() => this.props.history.goBack()}>
                    <Button key="back" size="default">
                      取消
                    </Button>
                  </Popconfirm>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>
        <FooterToolbar />
      </PageHeaderLayout>
    );
  }
}
